<template>
  <div class="chunk_page">
    <el-button type="primary" @click="addEl">添加十万个元素</el-button>
    <div ref="addContainer"></div>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import { _chunkRender, browserChunkRender } from './chunkRender.js'
const arr = Array.from({ length: 10000 }, (_, i) => ({ id: i, content: `Item ${i}` }));
const addContainer = ref(null);
// 一次性渲染导致页面卡顿
const addEl = () => {
  // chunkRender(arr);
  const handleFn = (i, item) => {
    const div = document.createElement('div');
    div.textContent = item.content;
    addContainer.value.appendChild(div);
  }

  const _chunkFn = (task) => {
    setTimeout(() => {
      const _now = performance.now();
      task(() => performance.now() - _now <= 10);
    }, 1000)
  }
  _chunkRender(arr, handleFn, _chunkFn)
}

// 分批渲染
const chunkRender1 = (data) => {
  if(!data.length) return;

  let i = 0;
  function runNext() {
    if(i >= data.length) return;
    requestIdleCallback((idl) => {
      while(idl.timeRemaining() > 2 && i < data.length) {
        console.log("🚀 ~ requestIdleCallback ~ idl.timeRemaining():", idl.timeRemaining())
        const div = document.createElement('div');
        div.textContent = data[i].content;
        addContainer.value.appendChild(div);
        i++;
      }
      // 分片完成
      runNext();
    })
  }
  runNext();
}
</script>
<style>
</style>